package cn.edu.scnu.springbootcinema.controller;

import jakarta.servlet.RequestDispatcher;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller
public class ErrorController implements org.springframework.boot.web.servlet.error.ErrorController {

    @RequestMapping("/error")
    public String handleError(HttpServletRequest request, Model model) {
        // 获取错误状态码
        Object status = request.getAttribute(RequestDispatcher.ERROR_STATUS_CODE);

        if (status != null) {
            int statusCode = Integer.parseInt(status.toString());

            // 根据不同的状态码设置不同的错误信息
            if (statusCode == HttpStatus.NOT_FOUND.value()) {
                model.addAttribute("message", "您访问的页面不存在。");
            } else if (statusCode == HttpStatus.INTERNAL_SERVER_ERROR.value()) {
                model.addAttribute("message", "服务器内部错误，请稍后再试。");
            } else {
                model.addAttribute("message", "发生未知错误。");
            }
        }

        return "error";
    }
}
